/**
 * @author Stephan Pfaff (webmaster@derdaumen.net)
 */

$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form' || tag == 'fieldset') {
		    $(this).hideErrorMessages();
		    $(this).find('.thumb').each(function(){
		    	this.src = noImage;
		    	this.alt = 'Kein Bild vorhanden.';
		    	this.title = 'Kein Bild vorhanden.';
		    });
		    $(this).find('.img').each(function(){
		    	this.src = '';
		    	this.alt = '';
		    	this.title = '';
		    });
		    $(this).find('#btn_btn_dummy').hide();
		    $(this).find('#btn_content_dummy').hide();
			return $(':input',this).clearForm();
		}
		if (type == 'text' || type == 'password' || type == 'textarea' 
			|| type == 'file' || type == 'hidden')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};
$.fn.showError = function(message){
	if (!$(this).parent().hasClass('error')) {
		$(this).parent().addClass('error').find('label').before('<strong class="message_error">'+message+'</strong>');
	}
};
$.fn.hideErrorMessages = function() {
	$(this).find('.error').removeClass('error');
    $(this).find('.message_error').remove();
};

function updateCoords(c) {
	$('#img_crop_x').val(c.x);
	$('#img_crop_y').val(c.y);
	$('#img_crop_w').val(c.w);
	$('#img_crop_h').val(c.h);
};

function doPreview(coords) {
	if (parseInt(coords.w) > 0) {
		var rx = 75 / coords.w;
		var ry = 75 / coords.h;
		$('#crop_img_thumb').css({
			width: Math.round(rx * imgwidth) + 'px',
			height: Math.round(ry * imgheight) + 'px',
			marginLeft: '-' + Math.round(rx * coords.x) + 'px',
			marginTop: '-' + Math.round(ry * coords.y) + 'px'
		});
	}
};
function prepareCrop(response, crop) {
	$("#crop_img_orig").remove();
	$("#crop_img_thumb").remove();
	$(".jcrop-holder").Jcrop("destroy");
	$(".jcrop-holder").remove();

	if (response.pathname != null && response.pathname != '') {
		var newImg = new Image();
		$(newImg).load().attr('src', response.pathname+'?'+Math.floor(Math.random()*1001))
						.attr('id', 'crop_img_orig');
		imgwidth = response.imagewidth;
		imgheight = response.imageheight;
		$('#crop_orig_container').append(newImg);
		
		if (crop) {
			$(newImg).Jcrop({
				aspectRatio: 1,
				setSelect: [0, 0, 75, 75],
				onChange: doPreview,
				onSelect: doPreview,
				onSelect: updateCoords
			});
			var newThumb = new Image();
			$(newThumb).load().attr('src', response.pathname+'?'+Math.floor(Math.random()*1001))
								.attr('id', 'crop_img_thumb');
			$('#crop_thumb_container').append(newThumb);
			tempPath = response.pathname;
		}
	}
};